package com.yfl.tingyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yfl.tingyu.mapper.RoleMenuMapper;
import com.yfl.tingyu.pojo.Role;
import com.yfl.tingyu.pojo.Role;
import com.yfl.tingyu.mapper.RoleMapper;
import com.yfl.tingyu.pojo.RoleMenu;
import com.yfl.tingyu.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2020-05-26
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public Map<String, Object> selectRole(Integer page, Integer rows) {

        //创建分页对象
        Page<Role> rolePage = new Page<>(page,rows);

        QueryWrapper<Role> qw=new QueryWrapper<>();

        Page<Role> companyPage = baseMapper.selectPage(rolePage, qw);

        //封装前端dataGraid需要的数据
        Map<String, Object> map = new HashMap<>();

        map.put("total",companyPage.getTotal());
        map.put("rows",companyPage.getRecords());

        return map;
    }

    //新增角色分配菜单
    @Override
    public Boolean insertOrUpdate(Role role, Integer[] mids) {

        //判断是新增还是更新
        if (role.getRid() != null){
            baseMapper.updateById(role);
        }else {

            int row = baseMapper.insert(role);
            if (row==0){
                return  false;
            }
        }
        //获取角色id
        Integer rid = role.getRid();

        //删除角色菜单中间表的原有数据
        QueryWrapper<RoleMenu> qw=new QueryWrapper<>();
        qw.eq("rid",rid);
        int i = roleMenuMapper.delete(qw);
        if (i==0){
            return  false;
        }

        //循环插入新的菜单id
        for (Integer mid : mids) {

            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMid(mid);
            roleMenu.setRid(rid);

            int insert = roleMenuMapper.insert(roleMenu);
            if (insert==0){
                return false;
            }

        }


        return true;
    }

    //删除操作
    @Override
    public Boolean removeRoleMenu(Integer[] rids) {

        //删除role表的数据
        QueryWrapper<Role> qw=new QueryWrapper<>();
        qw.in("rid",rids);
        int delete = baseMapper.delete(qw);

        //删除角色菜单中间表的数据
        QueryWrapper<RoleMenu> querywrapper=new QueryWrapper<>();
        querywrapper.in("rid",rids);
        int delete1 = roleMenuMapper.delete(querywrapper);
        if (delete == 0 || delete1 == 0){
            return false;
        }
        return true;
    }
}
